<template>
  <section>
    <SearchBar>
      <SearchBarItem :label="$t('taskLogList.project')">
        <a-select :placeholder="$t('operation.select')" v-model:value="searchForm.projectId" :select="initHandlers(searchForm.projectId)" allow-clear>
          <a-select-option v-for="item in projects" :key="item.projectId">{{ item.projectName }}</a-select-option>
        </a-select>
      </SearchBarItem>
      <SearchBarItem :label="$t('taskLogList.mockHandler')">
        <a-select :placeholder="$t('operation.select')" v-model:value="searchForm.handlerId" :disabled="!searchForm.projectId" allow-clear>
          <a-select-option v-for="item in handlers" :key="item.handlerId">{{ item.name }}</a-select-option>
        </a-select>
      </SearchBarItem>
      <SearchBarItem :label="$t('taskLogList.name')">
        <a-input :placeholder="$t('operation.enter')" v-model:value="searchForm.name" allow-clear />
      </SearchBarItem>
      <SearchBarItem :label="$t('taskLogList.taskCode')">
        <a-input :placeholder="$t('operation.enter')" v-model:value="searchForm.taskCode" allow-clear />
      </SearchBarItem>
      <SearchBarItem last>
        <a-button class="mr-6" danger type="primary" @click="preBatchDelete">
          {{$t('taskLogList.batchDelete')}}
        </a-button>
        <a-button type="primary" @click="search">
          <template #icon>
            <search-outlined />
          </template>
          {{$t('operation.search')}}
        </a-button>
      </SearchBarItem>
    </SearchBar>
    <a-table
      :columns="columns"
      :row-key="record => record.logId"
      :data-source="dataSource"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :scroll="{ x: 1500}"
    >
      <template #headerCell="{ column }">
        <template v-for="(item, index) in columns" :key="index">
          <span v-if="column.dataIndex && column.dataIndex === item.dataIndex">
          {{ $t(column.title) }}
          </span>
        </template>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'action'">
          <a-popconfirm
            :title="$t('message.confirm_delete')"
            :ok-text="$t('operation.confirm')"
            :cancel-text="$t('operation.cancel')"
            placement="left"
            @confirm="deleteRow(record)"
          >
            <a-button danger size="small">{{$t('taskLogList.delete')}}</a-button>
          </a-popconfirm>
        </template>
        <template v-if="column.dataIndex === 'action_req'">
          <a-button class="mr-4" type="primary" size="small" @click="showReq(record)">{{$t('taskLogList.requestInfo')}}</a-button>
        </template>
        <template v-if="column.dataIndex === 'action_res'">
          <a-button class="mr-4" type="primary" size="small" @click="showRes(record)">{{$t('taskLogList.responseInfo')}}</a-button>
        </template>
      </template>
    </a-table>
    <TaskLogRequestInfo v-model:visible="visibleReq" :form="currentTaskLog?.requestInfo"/>
    <TaskLogResponseInfo v-model:visible="visibleRes" :form="currentTaskLog?.responseInfo"/>
    <BatchDeleteTaskLogModal v-model:visible="visibleBatchDel" :form="searchForm" :projects="projects" :projectIdHandlerInfoMap="projectIdHandlerInfoMap" :handlers="handlers" @ok="search" />
  </section>
</template>

<script lang="ts" setup>
import {APIResult} from "@/request";
import {MockTaskLogResult} from "@/store/taskLog";
import TaskLogRequestInfo from "./TaskLogRequestInfoModal.vue";
import TaskLogResponseInfo from "./TaskLogResponseInfoModal.vue";
import BatchDeleteTaskLogModal from "./BatchDeleteTaskLogModal.vue";
import { useRouter,useRoute } from "vue-router";

// 日志查询使用和进行中任务一样的项目/处理器二级联动,外加任务名称,任务编码查询
// 删除逻辑和取消注册类似,指定删除类型进行删除
const columns = [
  // {
  //   title: 'ID',
  //   dataIndex: 'logId',
  // },
  {
    title: 'taskLogList.taskCode',
    dataIndex: 'taskCode',
    fixed: 'left'
  },
  {
    title: 'taskLogList.name',
    dataIndex: 'name',
    fixed: 'left'
  },{
    title: 'taskLogList.project',
    dataIndex: 'projectName',
  }, {
    title: 'taskLogList.mockHandler',
    dataIndex: 'handlerName',
  },
  {
    title: 'taskLogList.registrationTime',
    dataIndex: 'registrationTime',
  },
  {
    title: 'taskLogList.requestStartTime',
    dataIndex: 'requestTime',
  },
  {
    title: 'taskLogList.timing',
    dataIndex: 'timing',
  },  {
    title: 'taskLogList.responseStatus',
    dataIndex: 'responseStatus',
  },
  {
    title: 'taskLogList.requestInfo',
    dataIndex: 'action_req',
  },
  {
    title: 'taskLogList.responseInfo',
    dataIndex: 'action_res',
  },
  {
    title: 'table.action',
    dataIndex: 'action',
    fixed: 'right',
    width: '100px',
  },
]
const searchForm = reactive({
  projectId: void 0,
  handlerId: void 0,
  name: void 0,
  taskCode: void 0,
  deleteType: 1,
})

const queryData = (params: Record<string, any>): Promise<{ data: APIResult<MockTaskLogResult[]> }> => {
  return request.post('/api/dynamic-mock/mock/task/log/query', { ...params })
}

const { data: dataSource, run, loading, pagination } = usePagination(queryData, { totalKey: 'total' })

const handleTableChange = (pag: { pageSize: number; current: number ;}, filters: any, sorter: any) => {
  filters.role = filters.role?.join(',')
  Object.assign(searchForm, filters)
  pagination.current=pag.current;
  pagination.pageSize = pag.pageSize
  run({
    // sortField: sorter.field,
    // sortOrder: sorter.order,
    ...searchForm,
    pageNum: pagination.current,
    pageSize: pagination.pageSize,
  })
}

const update = () => {
  run({
    ...searchForm,
    pageNum: pagination.current,
    pageSize: pagination.pageSize,
  })
}

const search = () => {
  pagination.current = 1
  update()
}

const visibleBatchDel = ref(false)

const preBatchDelete=()=>{
// 批量删除
  visibleBatchDel.value = true;
}

const deleteRow= async (record)=>{
  // 删除行
  if (record) {
    const deleteRowParam= {
      logId:record.logId,
      deleteType:DeleteTaskLogTypeEnums.ALL
    };

   await request.post('/api/dynamic-mock/mock/task/log/del', deleteRowParam)
    update()
  }
}

const currentTaskLog = ref()

const visibleReq = ref(false)

const showReq=(record: MockTaskLogResult)=>{
// 展示请求信息
  currentTaskLog.value = toRaw(record)
  visibleReq.value = true;
}

const visibleRes = ref(false)

const showRes=(record: MockTaskLogResult)=>{
// 展示响应信息
  currentTaskLog.value = toRaw(record)
  visibleRes.value = true;
}


const projects = ref([])
const queryProjects = async () => {
  const res = await request.post('/api/dynamic-mock/project/queryOwnAll', {})
  projects.value = res.data?.data
}
queryProjects()

const projectIdHandlerInfoMap = ref({})
const queryProjectIdHandlerInfoMap = async () => {
  const res = await request.post('/api/dynamic-mock/mock/handler/queryOwn', {})
  projectIdHandlerInfoMap.value = res.data?.data.projectHandlerMap
}

queryProjectIdHandlerInfoMap()

const handlers=ref([])

const initHandlers=(projectId)=>{
  handlers.value=projectIdHandlerInfoMap.value[projectId]
  searchForm.handlerId=''
}

const route = useRoute();

const init = () => {
  if (route.params.taskCode) {
    searchForm.taskCode = route.params.taskCode;
  }
  search()
}

init();

</script>

<style></style>
